import React, { useEffect, useRef, useState } from 'react'
import styles from './index.module.scss'
import classnames from 'classnames'
import Icon from '@/components/Icon'

export default function Img({ src, className, alt }) {
	// 记录图片加载是否出错的状态
	const [isError, setIsError] = useState(false)
	// 记录图片是否正在加载的状态
	const [isLoading, setIsLoading] = useState(true)
	const imgRef = useRef(null)

	useEffect(() => {
		// 监听图片
		const observer = new IntersectionObserver(([{ isIntersecting }]) => {
			if (isIntersecting) {
				// 图片在可视区
				imgRef.current.src = imgRef.current.dataset.src
				// 取消监听
				observer.unobserve(imgRef.current)
			}
		})

		observer.observe(imgRef.current)
	}, [])

    const onLoad = () => {
        setIsError(false)
        setIsLoading(false)
    }

    const onError = () => {
        setIsLoading(false)
        setIsError(true)
    }

	return (
		<div className={classnames(styles.root, className)}>
			{isLoading && (
				<div className="image-icon">
					<Icon type="iconphoto" />
				</div>
			)}

			{isError && (
                <div className='image-icon'>
                    <Icon type="iconphoto-fail"/>
                </div>
            )}

			<img
				alt={alt}
				data-src={src}
				ref={imgRef}
				onLoad={onLoad}
				onError={onError}
			/>
		</div>
	)
}
